#!/usr/bin/env python

import sys, getopt, switch

def usage():
	print "usage: dump_config [-h] [-a address] [-f filename]"
	print "\t-a or --address\t specify the IP address of the switch"
	print "\t(if not specified the command will be executed on every switchs)"
	print "\t-f or --file\t specify the name of the file where the configuration will be saved"
	print "\t-h\t\t display this help"
	print

def dump_config(list_switchs, file):
	for ip in list_switchs:
		print "Connecting to " + ip + "..."
		tn = switch.connect(ip)
		if not tn:
			print "Error while connecting to " + ip
			continue
		name = switch.enable(tn)
		if not name:
			print "Error while connecting to " + ip
			continue
		print "Connected on " + name
		if file == "":
			filename = name + ".conf"
		else:
			filename = file
		print "Dumping the configuration in the file \"" + filename + "\"..."
		infos = switch.dump_config(tn, filename)
		if infos.find("!!!") == -1:
			print infos
		else:
			print "Done"
		switch.quit(tn)
		print

def main(argv):
	try:
		opts, args = getopt.getopt(argv[1:], "a:f:h", ["help", "address=", "file="])
	except getopt.GetoptError:
		usage()
		sys.exit(2)
	list_switchs = []
	file = ""
	for opt, arg in opts:
		if opt in ("-h", "--help"):
			usage()
			sys.exit()
		elif opt in ("-a", "--address"):
			list_switchs.append(arg)
		elif opt in ("-f", "--file"):
			file = arg
	if list_switchs == []:
		list_switchs = switch.get_switch_list()
	dump_config(list_switchs, file)

if __name__ == "__main__":
	main(sys.argv)
